'use strict';
const db = uniCloud.database();
const openVipCollection = db.collection('xxf-open-vip');
const dbCmd = db.command;

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('xxf-open-vip event : ', event);
	const {
		uid,
		action
	} = event;
	if (!uid && action) {
		return {
			msg: '用户ID参数错误！',
			code: 0,
			data: null
		};
	}
	switch (action) {
		case 'putOpenVipOrder':
			return putOpenVipOrder(event);
		case 'payOpenVipOrder':
			return payOpenVipOrder(event);
		case 'checkOpenVipOrderStatus':
			return checkOpenVipOrderStatus(event);
		default:
			return {
				msg: 'Invalid action！',
					code: 0,
					data: null
			};
	}
};

async function checkOpenVipOrderStatus(params) {
	console.log("checkOpenVipOrderStatus: ", params);
	const {
		uid,
		openId,
		orderId,
	} = params;
	let openOrderRes = await openVipCollection.where({
		_id: orderId
	}).get();
	console.log("openOrderRes: ", openOrderRes);
	if (openOrderRes && openOrderRes.data && openOrderRes.data.length) {
		const openOrderItem = openOrderRes.data[0];
		let queryRes = null;
		try {
			if (openOrderItem.notify_info && openOrderItem.notify_info.transactionId) {
				queryRes = await uniCloud.callFunction({
					name: 'xxf-uniPay',
					data: {
						action: "orderQuery",
						transactionId: openOrderItem.notify_info.transactionId,
					}
				});
			} else {
				queryRes = await uniCloud.callFunction({
					name: 'xxf-uniPay',
					data: {
						action: "orderQuery",
						outTradeNo: openOrderItem._id,
					}
				});
			}
			console.log("payOrder queryRes: ", queryRes);
		} catch (err) {
			console.log("payOrder queryErr: ", err);
			queryRes = {};
		}
		if (queryRes.result && queryRes.result.code === 1) {
			// 订单已支付
			console.log("已支付: ");
			const nowTime = Date.now();
			const updateRes = await openVipCollection.where({
				_id: orderId
			}).update({
				update_time: nowTime,
				pay_time: nowTime,
				status: '2', // 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；
				total_money: queryRes.result.data.totalFee,
				discount: 0,
				pay_money: queryRes.result.data.totalFee,
				notify_info: queryRes.result.data,
			});
			console.log("updateRes: ", updateRes);
			if (updateRes.updated === 1) {
				return {
					msg: '订单已支付！',
					code: 1,
					data: true
				}
			}
		}
		return {
			msg: '订单未支付！',
			code: 1,
			data: false
		}
	}
	return {
		msg: '订单不存在！',
		code: 1,
		data: false
	}
}

async function payOpenVipOrder(params) {
	console.log("payOpenVipOrder: ", params);
	const {
		uid,
		openId,
		orderId,
	} = params;
	if (orderId) {
		let orderRes = await openVipCollection.where({
			_id: orderId
		}).get();
		console.log("orderRes: ", orderRes);
		if (orderRes && orderRes.data && orderRes.data.length) {
			const orderItem = orderRes.data[0];
			if (orderItem.status === '1') {
				let checkRes = await checkOpenVipOrderStatus(params);
				if (checkRes.result && checkRes.result.data) {
					return {
						msg: '订单已支付！',
						code: 1,
						data: checkRes.result.data
					}
				} else {
					// 前往支付
					console.log("前往支付: ");
					let title = "‘硒乡坊’开通会员";
					const unipayRes = await uniCloud.callFunction({
						name: 'xxf-uniPay',
						data: {
							action: "getOrderInfo",
							openId,
							orderNo: orderItem._id,
							money: orderItem.need_money,
							title,
						}
					});
					console.log('unipayRes:', unipayRes);
					return unipayRes.result;
				}
			} else {
				return {
					msg: '订单有误！',
					code: 0,
					data: null
				}
			}
		} else {
			// 不存在
			return {
				msg: '订单ID不存在！',
				code: 0,
				data: null
			}
		}
	}
}

async function putOpenVipOrder(params) {
	const {
		uid,
		totalMoney,
		discount,
		payMoney,
		needMoney
	} = params;
	const nowTime = Date.now();
	const addRes = await openVipCollection.add({
		uid,
		create_time: nowTime,
		update_time: nowTime,
		pay_time: 0,
		status: '1', // 1-待支付；2-已支付；3-已发货；4-已收货；5-已失效；6-已退款；
		total_money: totalMoney,
		discount,
		need_money: needMoney
	});
	console.log("addRes: ", addRes.id);
	if (addRes && addRes.id) {
		const whereRes = await openVipCollection.where({
			uid,
			_id: addRes.id,
		}).get();
		console.log("whereRes: ", whereRes);
		if (whereRes && whereRes.data && whereRes.data.length) {
			const orderObj = whereRes.data[0];
			return {
				msg: '',
				code: 1,
				data: {
					...orderObj
				}
			}
		}
	} else {
		return {
			msg: '下单出错！',
			code: 0,
			data: null
		}
	}
}